package com.cheval.rpcframe.protocal;

import com.cheval.rpcframe.common.Config;
import org.apache.catalina.*;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;
import org.apache.log4j.Logger;


public class ProviderServer {

    private static Logger logger = Logger.getLogger(ProviderServer.class);

    public static void startRPCServer(String hostname, int port) {
        String serverType = Config.getServerType();
        if ("tomcat".equalsIgnoreCase(serverType)) {
            startTomcat(hostname, port);
        }
    }

    private static void startTomcat(String hostname, int port) {
        String contextPath = "";
        Context context = new StandardContext();
        context.setPath(contextPath);
        context.addLifecycleListener(new Tomcat.FixContextListener());

        Host host = new StandardHost();
        host.setName(hostname);
        host.addChild(context);

        Engine engine = new StandardEngine();
        engine.setDefaultHost(hostname);
        engine.addChild(host);

        Connector connector = new Connector();
        connector.setPort(port);

        Tomcat tomcat = new Tomcat();
        Server server = tomcat.getServer();
        Service service = server.findService("Tomcat");
        service.setContainer(engine);
        service.addConnector(connector);
        tomcat.addServlet(contextPath, "dispatcher", new DispatcherServlet());
        context.addServletMappingDecoded("/*", "dispatcher");

        try {
            tomcat.start();
            tomcat.getServer().await();
        } catch (LifecycleException e) {
            logger.error("tomcat start error!", e);
        }
    }
}
